<?php

/**
 * @file
 * Contains \Drupal\libsys\Plugin\QueueWorker\UpdatePhoto.
 */

namespace Drupal\libsys\Plugin\QueueWorker;

use Drupal\Core\Queue\QueueWorkerBase;

/**
 * Updates a reader's photo.
 *
 * @QueueWorker(
 *   id = "libsys_photo_exchange",
 *   title = @Translation("Reader\'s Photo Exchange"),
 *   cron = {"time" = 60}
 * )
 */
class UpdatePhoto extends QueueWorkerBase {

  /**
   * {@inheritdoc}
   */
  public function processItem($reader_info) {
	$reader=$reader_info->smt_salaryno;
	$photo=$reader_info->smt_photo;

	// First let's fetch all the database settings
	$libsys_database = \Drupal::config('libsys.datasource');
	
	try {
		// Use php-oci8 rather than pdo_oci to deal with blob data, which is faster
		$conn=oci_connect($libsys_database->get('username'), $libsys_database->get('password'),
			sprintf("%s:%s/%s", $libsys_database->get('host'), $libsys_database->get('port'), $libsys_database->get('database')), 'AL32UTF8'
		);
		if(!$conn) {
			$e=oci_error();
			throw new \Exception($e['message']);
		}
		
		if(!empty($photo)) {
			// Get CERT_ID from barcode
			$sql=sprintf("SELECT * FROM READER_CERT WHERE REDR_CERT_ID='%s'", $reader);
			$stmt = oci_parse($conn, $sql);
			if(!$stmt) {
				$e=oci_error($stmt);
				throw new \Exception($e['message']);
			}
			$r=oci_execute($stmt, OCI_DEFAULT);
			if(!$r) {
				$e=oci_error($stmt);
				throw new \Exception($e['message']);
			}
			$row = oci_fetch_assoc($stmt);
			$reader=$row['CERT_ID'];

			if(empty($reader)) throw new \InvalidArgumentException();
			
			// First let's remove the old picture.
			$sql=sprintf("DELETE READER_PORTRAIT WHERE P_CERT_ID='%s'", $reader);
			$stmt = oci_parse($conn, $sql);
			if(!$stmt) {
				$e=oci_error($stmt);
				throw new \Exception($e['message']);
			}
			$r=oci_execute($stmt, OCI_DEFAULT);
			if(!$r) {
				$e=oci_error($stmt);
				throw new \Exception($e['message']);
			}
			oci_commit($conn);
			oci_free_statement($stmt);

			// Now let's fill the photo
			$sql=sprintf("INSERT INTO READER_PORTRAIT(REARDER_PORTRAIT, P_CERT_ID) VALUES (hextoraw('%s'), '%s')", $photo, $reader);
			$sql='INSERT INTO READER_PORTRAIT(REARDER_PORTRAIT, P_CERT_ID) VALUES (:photo, :reader)';
			$stmt = oci_parse($conn, $sql);
			if(!$stmt) {
				$e=oci_error($stmt);
				throw new \Exception($e['message']);
			}
			oci_bind_by_name($stmt, ':photo', $photo, -1, SQLT_LBI);
			oci_bind_by_name($stmt, ':reader', $reader);
			$r=oci_execute($stmt, OCI_DEFAULT);
			if(!$r) {
				$e=oci_error($stmt);
				throw new \Exception($e['message']);
			} else {
				oci_commit($conn);
				\Drupal::logger('libsys')->info('Photo of @reader has been updated.',
					['@reader'=>$reader]
				);
			}
		}
	} catch (\InvalidArgumentException $e) {
		\Drupal::logger('libsys')->warning('@reader does not exist in database.',
			['@reader'=>$reader_info->smt_salaryno]
		);
	} catch (\Exception $e) {
		if(!empty($stmt))
			oci_free_statement($stmt);
		if(!empty($conn))
			oci_close($conn);
		throw new \Exception($e->getMessage());
	} finally {
		if(!empty($stmt))
			oci_free_statement($stmt);
		if(!empty($conn))
			oci_close($conn);
	}
  }
}
?>
